<template>
  <div class="device-logs">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备日志</span>
          <div class="header-actions">
            <el-select 
              v-model="selectedDevice" 
              placeholder="选择设备" 
              style="width: 200px; margin-right: 10px;"
              @change="loadDeviceLogs"
            >
              <el-option
                v-for="device in deviceOptions"
                :key="device.id"
                :label="device.name"
                :value="device.id"
              />
            </el-select>
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="margin-right: 10px;"
              @change="loadDeviceLogs"
            />
            <el-button type="primary" @click="loadDeviceLogs">查询</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="logList" v-loading="loading" stripe>
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="消息" />
        <el-table-column prop="device_id" label="设备ID" width="180" />
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getDeviceLogs, getDeviceOptions } from '@/api/device'
import { formatDate } from '@/utils/format'

interface Log {
  id: number
  timestamp: string
  level: string
  message: string
  device_id: string
}

interface DeviceOption {
  id: string
  name: string
}

const route = useRoute()
const loading = ref(false)
const logList = ref<Log[]>([])
const deviceOptions = ref<DeviceOption[]>([])
const selectedDevice = ref('')
const dateRange = ref<[Date, Date] | null>(null)

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loadDeviceOptions = async () => {
  try {
    const response = await getDeviceOptions()
    deviceOptions.value = response.data
  } catch (error) {
    ElMessage.error('获取设备列表失败')
    console.error(error)
  }
}

const loadDeviceLogs = async () => {
  if (!selectedDevice.value) {
    ElMessage.warning('请选择设备')
    return
  }
  
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      deviceId: selectedDevice.value,
      startTime: dateRange.value?.[0] ? dateRange.value[0].toISOString() : undefined,
      endTime: dateRange.value?.[1] ? dateRange.value[1].toISOString() : undefined
    }
    const response = await getDeviceLogs(params)
    logList.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取设备日志失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const getLevelType = (level: string) => {
  switch (level.toLowerCase()) {
    case 'error': return 'danger'
    case 'warn': return 'warning'
    case 'info': return 'primary'
    default: return 'info'
  }
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadDeviceLogs()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadDeviceLogs()
}

onMounted(() => {
  loadDeviceOptions()
  
  // 如果路由中有设备ID，则选中该设备
  if (route.params.deviceId) {
    selectedDevice.value = route.params.deviceId as string
    loadDeviceLogs()
  }
})
</script>

<style scoped lang="scss">
.device-logs {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>